package cc.example.mybatislike.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = {"com.example.mybatislike.db.zeus"},
    sqlSessionFactoryRef = "zeusSqlSessionFactory",
    sqlSessionTemplateRef = "zeusSqlSessionTemplate")
public class ZeusMybatisSourceConfig {

  @Bean(name = "zeusDataSource")
  @Qualifier("zeusDataSource")
  @ConfigurationProperties("spring.datasource.zeus")
  public DataSource dataSourceZeus() {
    return new HikariDataSource();
  }

  @Bean(name = "zeusSqlSessionFactory")
  public MybatisSqlSessionFactoryBean hermesMybatisSqlSessionFactoryBean(@Qualifier("zeusDataSource") DataSource hermesLinkDataSource) {
    MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
    factoryBean.setDataSource(hermesLinkDataSource);
    return factoryBean;
  }

  @Bean("zeusMybatisTransactionManager")
  public DataSourceTransactionManager transactionManager(@Qualifier("zeusDataSource") DataSource zeusDataSource) {
    return new DataSourceTransactionManager(zeusDataSource);
  }

  @Bean("zeusSqlSessionTemplate")
  public SqlSessionTemplate sqlsessiontemplate(@Qualifier("zeusSqlSessionFactory") SqlSessionFactory sessionFactory) {
    return new SqlSessionTemplate(sessionFactory);
  }
}
